﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;

namespace NewSeasonFinder
{
    public partial class FolderManage : Form
    {
        private XmlDocument xmlDoc = new XmlDocument();
        private bool isChanged = false;

        public FolderManage()
        {
            InitializeComponent();
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form_FolderSelect_Load(object sender, EventArgs e)
        {
            XmlElement xe = xmlDoc.CreateElement(NameStrings.FLODERS);
            xmlDoc.AppendChild(xe);
            //读取文件夹
            if (File.Exists(NameStrings.FILENAME_FOLDER))
            {
                XmlDocument _xmlDoc = new XmlDocument();
                _xmlDoc.Load(NameStrings.FILENAME_FOLDER);
                foreach (XmlNode xn_folderPath in _xmlDoc.SelectSingleNode(NameStrings.FLODERS).ChildNodes)
                {
                    if (xn_folderPath.Name == NameStrings.FLODER)
                    {
                        //一般文件夹
                        FolderListAdd(xn_folderPath.InnerText, 0);
                    }
                    else if (xn_folderPath.Name == NameStrings.SHAREFLODER)
                    {
                        //共享文件夹
                        FolderListAdd(xn_folderPath.InnerText, 2);
                    }
                }
            }
            xmlDoc.Save(NameStrings.FILENAME_FOLDER);

            //禁止创建新文件夹
            folderBrowserDialog1.ShowNewFolderButton = false;

            //删除按钮初始无效
            button_Del.Enabled = false;
        }

        /// <summary>
        /// 文件夹选择按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //选择文件夹窗口
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //当为有效文件夹,可以使用添加按钮,否则不可使用
                if (Directory.Exists(folderBrowserDialog1.SelectedPath))
                {
                    //检查文件夹是否已经存在于列表,如不存在则添加入
                    if (FolderListAdd(folderBrowserDialog1.SelectedPath, 0) == 1)
                    {
                        MessageBox.Show("您所选择的文件夹已存在于文件夹列表", "文件夹已存在", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        isChanged = true;
                    }
                }
            }
        }

        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Del_Click(object sender, EventArgs e)
        {
            if (listBox_FolderList.SelectedIndex >= 0)
            {

                XmlNode root = xmlDoc.SelectSingleNode(NameStrings.FLODERS);
                root.RemoveChild(root.ChildNodes[listBox_FolderList.SelectedIndex]);
                listBox_FolderList.Items.RemoveAt(listBox_FolderList.SelectedIndex);
                isChanged = true;
            }
        }
        
        /// <summary>
        /// 设置下载文件夹按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_DownloadFolder_Click(object sender, EventArgs e)
        {
            //选择文件夹窗口
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //当为有效文件夹,成功设置
                if (Directory.Exists(folderBrowserDialog1.SelectedPath))
                {
                    textBox_ShareFolder.Text = folderBrowserDialog1.SelectedPath;
                    isChanged = true;
                }
            }
        }

        /// <summary>
        /// 设置共享文件夹按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_ShareFolder_Click(object sender, EventArgs e)
        {
            //选择文件夹窗口
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //当为有效文件夹，成功设置
                if (Directory.Exists(folderBrowserDialog1.SelectedPath) &&　FolderListAdd(folderBrowserDialog1.SelectedPath, 2) == 0)
                {
                    isChanged = true;
                }
            }
        }

        /// <summary>
        /// 根据选择项控制删除按钮是否可用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox_FolderList_SelectedIndexChanged(object sender, EventArgs e)
        {
            //当列表不为空且所选不为空时,删除按钮可用
            if (listBox_FolderList.Items.Count > 0)
            {
                if (listBox_FolderList.SelectedIndex >= 0)
                {
                    button_Del.Enabled = true;
                    return;
                }
            }

            //否则删除按钮不可用
            button_Del.Enabled = false;
        }

        /// <summary>
        /// 确定按钮,存储并关闭窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_OK_Click(object sender, EventArgs e)
        {
            //存储文件列表
            xmlDoc.Save(NameStrings.FILENAME_FOLDER);
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }
        
        /// <summary>
        /// 取消按钮,关闭窗口但不进行存储
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Cancel_Click(object sender, EventArgs e)
        {
            if (isChanged == true)
            {
                switch (MessageBox.Show("所做修改尚未保存，是否现在保存？", "", MessageBoxButtons.YesNoCancel))
                {
                    case System.Windows.Forms.DialogResult.Yes:
                        {
                            xmlDoc.Save(NameStrings.FILENAME_FOLDER);
                        }
                        break;
                    case System.Windows.Forms.DialogResult.Cancel:
                        {
                            return;
                        }
                    default:
                        break;
                }
            }
            this.Close();
        }

        /// <summary>
        /// 将文件夹加入Xml
        /// </summary>
        /// <param name="newFolderPath">文件夹路径</param>
        /// <param name="type">0：存储文件夹 2：共享文件夹</param>
        private int FolderListAdd(string newFolderPath, int type)
        {
            newFolderPath = newFolderPath.ToLower();

            //将文件夹表读入列表
            XmlNode root = xmlDoc.SelectSingleNode(NameStrings.FLODERS);
            XmlNode curNode = xmlDoc.SelectSingleNode(NameStrings.FLODERS).FirstChild;

            XmlElement xe = null;
            if (type == 2)
            {
                //共享文件夹节点
                xe = xmlDoc.CreateElement(NameStrings.SHAREFLODER);
                xe.InnerText = newFolderPath;

                if (root.SelectSingleNode(NameStrings.SHAREFLODER) != null)
                {
                    root.SelectSingleNode(NameStrings.SHAREFLODER).InnerText = newFolderPath;
                }
                else
                {
                    root.AppendChild(xe);
                }
                textBox_ShareFolder.Text = newFolderPath;
                return 0;
            }
            else
            {
                //普通文件夹节点
                xe = xmlDoc.CreateElement(NameStrings.FLODER);
                xe.InnerText = newFolderPath;
            }          

            //如果为xmlDoc为空,直接插入
            if (curNode == null)
            {
                root.AppendChild(xe);
                listBox_FolderList.Items.Add(xe.InnerText);
                return 0;
            }

            int insertPos = 0;
            //遍历节点,是否有插入点
            while (curNode != null)
            {
                string folderPath = curNode.InnerText;
                int result = newFolderPath.CompareTo(folderPath);
                if (result == 0)
                {
                    //为相同文件夹,不添加
                    return 1;
                }
                else if (result < 0 || curNode.Name == NameStrings.SHAREFLODER)
                {
                    //"小"于现在文件夹 或 已经遍历到最后一个节点（SHAREFLODER通常为最后一个节点）
                    if (curNode.InnerXml.StartsWith(newFolderPath) && curNode.Name != NameStrings.SHAREFLODER)
                    {
                        //如果当前文件夹是新文件夹的子文件夹,则删除当前文件夹
                        XmlNode tempNode = curNode;
                        curNode = curNode.NextSibling;
                        root.RemoveChild(tempNode);
                    }
                    else
                    {
                        //"小"于当前文件夹,插入在现在的文件夹之前
                        root.InsertBefore(xe, curNode);
                        listBox_FolderList.Items.Insert(insertPos, xe.InnerText);
                        return 0;
                    }
                }
                else if (result > 0)
                {
                    //如果新文件夹是现有文件夹的子文件夹，则直接返回
                    if (newFolderPath.StartsWith(curNode.InnerText))
                    {
                        return 1;
                    }
                    //"大"于现在文件夹,向下继续查找
                    insertPos++;
                    curNode = curNode.NextSibling;
                }
            }

            //已有文件夹都比新文件夹路径"小"
            root.AppendChild(xe);
            listBox_FolderList.Items.Add(xe.InnerText);
            return 0;

        }

    }
}
